<?php

namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\CouponStatus;
use App\Models\Renting;
use App\Models\StoreCoupon;
use App\Models\StoreCouponUser;
use App\Service\CommonService;

class CouponController extends Controller
{
    /**
     * User: YKY
     * DateTime: 2022/11/14 16:55
     * @return array
     * 优惠券列表
     */
    public function couponlist()
    {
        try {
            $couponData = StoreCoupon::where('status','1')->select('id','coupon_price','title','integral')->get();
            return CommonService::success(200, '查询成功', $couponData);
        } catch (\Exception $e) {
            return CommonService::fail(9999, $e->getMessage(), '');
        }
    }

    /**
     * User: YKY
     * DateTime: 2022/11/14 16:55
     * @return array
     * 积分兑换优惠券
     */
    public function exchangeCoupon()
    {
        $uid=intval(request()->input('uid'));
        $cid=intval(request()->input('cid'));
        try {
            $coupon=StoreCoupon::where('id',$cid)->first();
            $user=Renting::where('id',$uid)->first();
            if ($coupon['integral']>$user['integral'])return commonService::fail(9999, '用户积分不够', '');
            if ($coupon['coupon_stock']==0)return commonService::fail(9999, '优惠券库存不足', '');

            $couponInfo=StoreCoupon::where('id',$cid)->first();
            $addData=[
                'uid'=>$uid,
                'cid'=>$cid,
                'coupon_title'=>$couponInfo['title'],
                'add_time'=>$couponInfo['add_time'],
                'end_time'=>time(),
                'integral'=>$coupon['integral']
            ];
            $userCoupon=StoreCouponUser::create($addData);
            Renting::where('id',$uid)->update(['integral'=>$user['integral']-$coupon['integral']]);
            if ($userCoupon) return commonService::success(200, '兑换成功', '');
        } catch (\Exception $e) {
            return commonService::fail(9999, $e->getMessage(), '');
        }
    }

    /**
     * User: YKY
     * DateTime: 2022/11/14 19:31
     * @return array
     * 个人优惠券查询
     */
    public function userCoupon()
    {
        $uid=request()->input('uid');
        $status=request()->input('status');
        try {
            $couponUser = StoreCouponUser::where(['uid'=>$uid,'status'=>$status])->select('id','coupon_price','coupon_title','status')->get();
            return commonService::success(200, '查询成功', $couponUser);
        } catch (\Exception $e) {
            return commonService::success(9999, $e->getMessage(), '');
        }
    }

    /**
     * User: YKY
     * DateTime: 2022/11/22 18:45
     * @return array
     * 优惠券状态表
     */
    public function couponStatus(){
        try {
            $couponData = CouponStatus::get();
            return CommonService::success(200, '查询成功', $couponData);
        } catch (\Exception $e) {
            return CommonService::fail(9999, $e->getMessage(), '');
        }
    }
}
